package edu.jd.homeworkteacher;

import edu.jd.common.Utils;
import edu.jd.homeworkstudent.HomeworkStudent;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class HomeworkTeaService {

    public int releaseHomework(String tea_id, String hk_title, String hk_req){
        SqlSession sess = Utils.openSession();
        try{
            HomeworkTeaDao dao = sess.getMapper(HomeworkTeaDao.class);
            Integer maxId = dao.getMaxHomeworkId();
            if(maxId==null) maxId = -1;
            int newId = maxId + 1;
            dao.insertHomework(newId, tea_id, hk_title, hk_req);
            sess.commit();
            return newId;
        }catch (Exception e){
            e.printStackTrace();
            sess.rollback();
            throw new RuntimeException("发布作业失败");
        }finally {
            sess.close();
        }
    }

    public void releaseToStudent(String tea_id, int newId){
        SqlSession sess = Utils.openSession();
        try{
            HomeworkTeaDao dao = sess.getMapper(HomeworkTeaDao.class);

            List<String> stuList = dao.getMyStudentId(tea_id);
            HomeworkStudent student = new HomeworkStudent(newId);
            for(String stuId : stuList){
                student.setStu_id(stuId);
                dao.insertHomeworkToStudent(student);
            }
            sess.commit();
        }catch (Exception e){
            e.printStackTrace();
            sess.rollback();
            throw new RuntimeException("发布作业失败");
        }finally {
            sess.close();
        }
    }

    public List<CorrectHomeworkDto> getSubmittedHomework(String tea_id){
        SqlSession sess = Utils.openSession();
        try{
            HomeworkTeaDao dao = sess.getMapper(HomeworkTeaDao.class);
            List<CorrectHomeworkDto> hkList = dao.getStudentsHomework(tea_id);
            sess.commit();
            return hkList;
        }catch (Exception e){
            e.printStackTrace();
            sess.rollback();
            throw new RuntimeException("获取作业失败");
        }finally {
            sess.close();
        }
    }

    public void correctHomework(int hk_id, String stu_id, int score, String tea_feedback){
        SqlSession sess = Utils.openSession();
        try{
            HomeworkTeaDao dao = sess.getMapper(HomeworkTeaDao.class);
            dao.updateCorrectHomework(hk_id, stu_id, score, tea_feedback);
            sess.commit();
        }catch (Exception e){
            e.printStackTrace();
            sess.rollback();
            throw new RuntimeException("批改作业失败");
        }finally {
            sess.close();
        }
    }
}
